import { Module,MiddlewareConsumer,RequestMethod } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserModule } from './modules/user/user.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from 'nestjs-config';
import { PostsModule } from './modules/posts/posts.module';
import { RoleModule } from './modules/role/role.module';
import path from 'path'
import {LogMiddleware} from './middlewares/log.middleware'
import {LoginMiddleware} from './middlewares/login.middleware'
@Module({
  imports: [
    // 配置加载配置文件
    ConfigModule.load(path.resolve(__dirname, 'config', '**/!(*.d).{ts,js}'), {
      modifyConfigName: name => name.replace('.config', ''),
    }),
    //mysql的连接
    TypeOrmModule.forRootAsync({
      useFactory: async (config: ConfigService) => ({
        name: config.get('database.name'),
        type: config.get('database.type'),
        host: config.get('database.host'),
        port: config.get('database.port'),
        username: config.get('database.username'),
        password: config.get('database.password'),
        database: config.get('database.database'),
        entities: [__dirname + '/**/*.entity{.ts,.js}'],
        logging: config.get('database.logging'),
      }),
      inject: [ConfigService],
    }),
    // TypeOrmModule.forRoot({
    //   type: 'mysql',
    //   host: '47.116.70.142',
    //   port: 3306,
    //   username: 'root',
    //   password: 'ldx-123456',
    //   database: 'nest',
    //   synchronize: true, // 自动同步数据模型到数据表中
    //   logging: true,
    //   entities: [
    //     __dirname + '/**/*.entity{.ts,.js}'
    //   ],
    // }),
    UserModule,
    PostsModule,
    RoleModule
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule implements MiddlewareConsumer { 
  apply:any
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(LogMiddleware,LoginMiddleware)
      .forRoutes({ path: '*', method: RequestMethod.ALL });
  }
}
